<template>
  <view class="page">
    <!-- 搜索栏 -->
    <view class="search-header">
      <view class="search-container">
        <view class="search-input-box">
          <uni-icons type="search" size="20" color="#999"></uni-icons>
          <input class="search-input" 
                 type="text" 
                 placeholder="搜索商品" 
                 v-model="searchKeyword"
                 @input="onSearchInput"
                 @confirm="onSearchConfirm"
                 focus>
          <uni-icons v-if="searchKeyword" 
                    type="closeempty" 
                    size="20" 
                    color="#999" 
                    @tap="clearSearch"></uni-icons>
        </view>
        <text class="search-btn" @tap="onSearchConfirm">搜索</text>
      </view>
    </view>

    <!-- 搜索建议 -->
    <view class="search-suggestions" v-if="showSuggestions && suggestions.length > 0">
      <view v-for="(suggestion, index) in suggestions" 
            :key="index" 
            class="suggestion-item"
            @tap="selectSuggestion(suggestion)">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <text class="suggestion-text">{{ suggestion }}</text>
      </view>
    </view>

    <!-- 搜索历史和热门搜索 -->
    <view class="search-content" v-if="!showSuggestions">
      <!-- 搜索历史 -->
      <view class="history-section" v-if="searchHistory.length > 0">
        <view class="section-header">
          <text class="section-title">搜索历史</text>
          <uni-icons type="trash" size="20" color="#999" @tap="clearHistory"></uni-icons>
        </view>
        <view class="tag-list">
          <view v-for="(item, index) in searchHistory" 
                :key="index" 
                class="tag-item"
                @tap="selectHistory(item)">
            <text class="tag-text">{{ item }}</text>
          </view>
        </view>
      </view>

      <!-- 热门搜索 -->
      <view class="hot-section">
        <view class="section-header">
          <text class="section-title">热门搜索</text>
        </view>
        <view class="tag-list">
          <view v-for="(item, index) in hotSearches" 
                :key="index" 
                class="tag-item hot-tag"
                @tap="selectHotSearch(item)">
            <text class="tag-text">{{ item }}</text>
          </view>
        </view>
      </view>

      <!-- 推荐商品 -->
      <view class="recommend-section">
        <view class="section-header">
          <text class="section-title">为你推荐</text>
        </view>
        <view class="recommend-grid">
          <view v-for="(product, index) in recommendProducts" 
                :key="index" 
                class="recommend-item"
                @tap="goToDetail(product.id)">
            <image class="recommend-image" :src="product.image" mode="aspectFill"></image>
            <view class="recommend-info">
              <text class="recommend-title">{{ product.title }}</text>
              <view class="recommend-price">
                <text class="price-symbol">¥</text>
                <text class="price-value">{{ product.price }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-results" v-if="showResults">
      <!-- 结果统计 -->
      <view class="result-header">
        <text class="result-count">找到{{ totalCount }}件相关商品</text>
        <view class="sort-options">
          <view v-for="(sort, index) in sortOptions" 
                :key="index"
                class="sort-item"
                :class="{ 'active': currentSort === index }"
                @tap="selectSort(index)">
            <text class="sort-text">{{ sort.name }}</text>
            <uni-icons v-if="sort.hasArrow" 
                      :type="currentSort === index && sortOrder === 'desc' ? 'arrowup' : 'arrowdown'" 
                      size="12" 
                      :color="currentSort === index ? '#ff4757' : '#999'"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 商品列表 -->
      <scroll-view class="result-list" 
                   scroll-y 
                   @scrolltolower="loadMore"
                   :refresher-enabled="true"
                   :refresher-triggered="refreshing"
                   @refresherrefresh="onRefresh">
        <view class="product-list">
          <view v-for="(product, index) in searchResults" 
                :key="product.id" 
                class="product-item"
                @tap="goToDetail(product.id)">
            <view class="product-image-container">
              <image class="product-image" :src="product.image" mode="aspectFill"></image>
              <view class="product-tag" v-if="product.tag">{{ product.tag }}</view>
            </view>
            <view class="product-info">
              <text class="product-title">{{ highlightKeyword(product.title) }}</text>
              <text class="product-subtitle" v-if="product.subtitle">{{ product.subtitle }}</text>
              <view class="price-section">
                <view class="current-price">
                  <text class="price-symbol">¥</text>
                  <text class="price-value">{{ product.price }}</text>
                </view>
                <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
              </view>
              <view class="product-meta">
                <text class="sales-count">已售{{ product.sales }}</text>
                <view class="rating" v-if="product.rating">
                  <uni-icons type="star-filled" size="12" color="#FFD700"></uni-icons>
                  <text class="rating-text">{{ product.rating }}</text>
                </view>
                <text class="shop-name" v-if="product.shopName">{{ product.shopName }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore">
          <uni-load-more :status="loadStatus"></uni-load-more>
        </view>
        
        <!-- 没有更多数据 -->
        <view class="no-more" v-if="!hasMore && searchResults.length > 0">
          <text class="no-more-text">没有更多商品了</text>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="searchResults.length === 0 && !loading && showResults">
          <image class="empty-image" src="/static/empty-search.png" mode="aspectFit"></image>
          <text class="empty-text">没有找到相关商品</text>
          <text class="empty-tip">试试其他关键词吧</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      showSuggestions: false,
      showResults: false,
      suggestions: [],
      searchHistory: [],
      hotSearches: [
        '手机', '耳机', '笔记本', '手表', '充电器',
        '数据线', '音响', '键盘', '鼠标', '平板'
      ],
      recommendProducts: [],
      searchResults: [],
      totalCount: 0,
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      refreshing: false,
      loadStatus: 'more',
      
      // 排序相关
      currentSort: 0,
      sortOrder: 'asc',
      sortOptions: [
        { name: '综合', key: 'default', hasArrow: false },
        { name: '销量', key: 'sales', hasArrow: true },
        { name: '价格', key: 'price', hasArrow: true },
        { name: '评价', key: 'rating', hasArrow: true }
      ],
      
      // 防抖定时器
      searchTimer: null
    }
  },
  
  onLoad(options) {
    // 加载搜索历史
    this.loadSearchHistory()
    
    // 加载推荐商品
    this.loadRecommendProducts()
    
    // 如果有传入的搜索关键词，直接搜索
    if (options.keyword) {
      this.searchKeyword = decodeURIComponent(options.keyword)
      this.performSearch()
    }
  },
  
  methods: {
    // 搜索输入事件
    onSearchInput() {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      
      if (this.searchKeyword.trim()) {
        this.showSuggestions = true
        this.showResults = false
        
        // 防抖处理
        this.searchTimer = setTimeout(() => {
          this.loadSuggestions()
        }, 300)
      } else {
        this.showSuggestions = false
        this.showResults = false
        this.suggestions = []
      }
    },
    
    // 搜索确认
    onSearchConfirm() {
      if (!this.searchKeyword.trim()) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        })
        return
      }
      
      this.performSearch()
    },
    
    // 执行搜索
    performSearch() {
      this.showSuggestions = false
      this.showResults = true
      
      // 保存搜索历史
      this.saveSearchHistory(this.searchKeyword)
      
      // 重置搜索结果
      this.searchResults = []
      this.currentPage = 1
      this.hasMore = true
      
      // 加载搜索结果
      this.loadSearchResults()
    },
    
    // 清空搜索
    clearSearch() {
      this.searchKeyword = ''
      this.showSuggestions = false
      this.showResults = false
      this.suggestions = []
    },
    
    // 加载搜索建议
    async loadSuggestions() {
      try {
        // 模拟API调用
        const mockSuggestions = [
          this.searchKeyword + '手机',
          this.searchKeyword + '配件',
          this.searchKeyword + '保护壳',
          this.searchKeyword + '充电器'
        ].filter(item => item !== this.searchKeyword)
        
        this.suggestions = mockSuggestions.slice(0, 5)
      } catch (error) {
        console.error('加载搜索建议失败:', error)
      }
    },
    
    // 选择搜索建议
    selectSuggestion(suggestion) {
      this.searchKeyword = suggestion
      this.performSearch()
    },
    
    // 加载搜索历史
    loadSearchHistory() {
      const history = uni.getStorageSync('searchHistory') || []
      this.searchHistory = history.slice(0, 10) // 最多显示10条
    },
    
    // 保存搜索历史
    saveSearchHistory(keyword) {
      let history = uni.getStorageSync('searchHistory') || []
      
      // 移除重复项
      history = history.filter(item => item !== keyword)
      
      // 添加到开头
      history.unshift(keyword)
      
      // 限制数量
      history = history.slice(0, 20)
      
      // 保存到本地
      uni.setStorageSync('searchHistory', history)
      this.searchHistory = history.slice(0, 10)
    },
    
    // 选择历史搜索
    selectHistory(keyword) {
      this.searchKeyword = keyword
      this.performSearch()
    },
    
    // 清空搜索历史
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('searchHistory')
            this.searchHistory = []
          }
        }
      })
    },
    
    // 选择热门搜索
    selectHotSearch(keyword) {
      this.searchKeyword = keyword
      this.performSearch()
    },
    
    // 加载推荐商品
    async loadRecommendProducts() {
      try {
        // 模拟API调用
        const mockProducts = [
          {
            id: 1,
            title: '智能手机',
            image: 'https://ai-public.mastergo.com/ai/img_res/0bb0de76012a21317548d7c11e047bf6.jpg',
            price: '1999'
          },
          {
            id: 2,
            title: '蓝牙耳机',
            image: 'https://ai-public.mastergo.com/ai/img_res/fa900c94f52fed4589e4b9eb9ea81fd7.jpg',
            price: '299'
          },
          {
            id: 3,
            title: '智能手表',
            image: 'https://ai-public.mastergo.com/ai/img_res/ffab28ea4d2c605e301b41dc31a81632.jpg',
            price: '399'
          },
          {
            id: 4,
            title: '笔记本电脑',
            image: 'https://ai-public.mastergo.com/ai/img_res/e2ad6b83b64864ad25cf6c2939f2b3c1.jpg',
            price: '4999'
          }
        ]
        
        this.recommendProducts = mockProducts
      } catch (error) {
        console.error('加载推荐商品失败:', error)
      }
    },
    
    // 加载搜索结果
    async loadSearchResults(refresh = false) {
      if (this.loading) return
      
      this.loading = true
      this.loadStatus = 'loading'
      
      if (refresh) {
        this.currentPage = 1
        this.hasMore = true
      }
      
      try {
        // 模拟API调用
        const response = await this.mockSearchApi()
        
        if (refresh) {
          this.searchResults = response.data
        } else {
          this.searchResults = [...this.searchResults, ...response.data]
        }
        
        this.totalCount = response.total
        this.hasMore = this.searchResults.length < this.totalCount
        this.currentPage++
        
      } catch (error) {
        console.error('搜索失败:', error)
        uni.showToast({
          title: '搜索失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.refreshing = false
        this.loadStatus = this.hasMore ? 'more' : 'noMore'
      }
    },
    
    // 模拟搜索API
    mockSearchApi() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const mockData = [
            {
              id: Date.now() + Math.random(),
              title: `${this.searchKeyword}相关商品 - 高品质智能设备`,
              subtitle: '正品保证，全国联保',
              image: 'https://ai-public.mastergo.com/ai/img_res/0bb0de76012a21317548d7c11e047bf6.jpg',
              price: '1999',
              originalPrice: '2999',
              sales: '1.2万',
              rating: '4.8',
              tag: '热销',
              shopName: '官方旗舰店'
            },
            {
              id: Date.now() + Math.random() + 1,
              title: `${this.searchKeyword}专业版 - 性能升级款`,
              subtitle: '专业级配置，性能强劲',
              image: 'https://ai-public.mastergo.com/ai/img_res/fa900c94f52fed4589e4b9eb9ea81fd7.jpg',
              price: '2999',
              originalPrice: '3999',
              sales: '8562',
              rating: '4.9',
              tag: '新品',
              shopName: '品牌直营店'
            }
          ]
          
          resolve({
            data: mockData,
            total: 50
          })
        }, 1000)
      })
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadSearchResults(true)
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadSearchResults()
      }
    },
    
    // 选择排序
    selectSort(index) {
      if (this.currentSort === index && this.sortOptions[index].hasArrow) {
        this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
      } else {
        this.currentSort = index
        this.sortOrder = 'asc'
      }
      
      // 重新加载数据
      this.loadSearchResults(true)
    },
    
    // 高亮关键词
    highlightKeyword(text) {
      if (!this.searchKeyword || !text) return text
      
      const keyword = this.searchKeyword.trim()
      if (!keyword) return text
      
      // 简单的高亮处理，实际项目中可能需要更复杂的处理
      return text.replace(new RegExp(keyword, 'gi'), `<span style="color: #ff4757;">${keyword}</span>`)
    },
    
    // 跳转到商品详情
    goToDetail(productId) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${productId}`
      })
    }
  },
  
  onUnload() {
    // 清除定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  }
}
</script>

<style>
.page {
  background-color: #f5f5f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.search-header {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-input-box {
  flex: 1;
  height: 64rpx;
  background-color: #f5f5f5;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  margin-right: 20rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  margin-left: 10rpx;
}

.search-btn {
  font-size: 28rpx;
  color: #ff4757;
}

.search-suggestions {
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.suggestion-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f8f8f8;
}

.suggestion-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 15rpx;
}

.search-content {
  flex: 1;
  padding: 30rpx;
}

.history-section, .hot-section, .recommend-section {
  margin-bottom: 40rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  background-color: #f5f5f5;
  border-radius: 20rpx;
  padding: 12rpx 24rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.hot-tag {
  background-color: #fff5f5;
  border: 1px solid #ff4757;
}

.tag-text {
  font-size: 24rpx;
  color: #666;
}

.hot-tag .tag-text {
  color: #ff4757;
}

.recommend-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.recommend-item {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  background-color: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recommend-image {
  width: 100%;
  height: 200rpx;
}

.recommend-info {
  padding: 20rpx;
}

.recommend-title {
  font-size: 24rpx;
  color: #333;
  line-height: 34rpx;
  height: 68rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 10rpx;
}

.recommend-price {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 20rpx;
  color: #ff4757;
}

.price-value {
  font-size: 26rpx;
  color: #ff4757;
  font-weight: bold;
}

.search-results {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.result-header {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-count {
  font-size: 24rpx;
  color: #999;
}

.sort-options {
  display: flex;
}

.sort-item {
  display: flex;
  align-items: center;
  margin-left: 30rpx;
}

.sort-item.active .sort-text {
  color: #ff4757;
}

.sort-text {
  font-size: 24rpx;
  color: #333;
  margin-right: 5rpx;
}

.result-list {
  flex: 1;
  background-color: #fff;
}

.product-list {
  padding: 0 30rpx;
}

.product-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-image-container {
  position: relative;
  margin-right: 20rpx;
}

.product-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
}

.product-tag {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  background-color: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-title {
  font-size: 28rpx;
  color: #333;
  line-height: 40rpx;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-subtitle {
  font-size: 24rpx;
  color: #666;
  line-height: 34rpx;
  margin-bottom: 10rpx;
}

.price-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 10rpx;
}

.current-price {
  display: flex;
  align-items: baseline;
  margin-right: 10rpx;
}

.original-price {
  font-size: 22rpx;
  color: #999;
  text-decoration: line-through;
}

.product-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sales-count {
  font-size: 22rpx;
  color: #999;
}

.rating {
  display: flex;
  align-items: center;
}

.rating-text {
  font-size: 22rpx;
  color: #999;
  margin-left: 4rpx;
}

.shop-name {
  font-size: 22rpx;
  color: #999;
}

.load-more {
  padding: 30rpx;
}

.no-more {
  padding: 30rpx;
  text-align: center;
}

.no-more-text {
  font-size: 24rpx;
  color: #999;
}

.empty-state {
  padding: 100rpx 30rpx;
  text-align: center;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 10rpx;
  display: block;
}

.empty-tip {
  font-size: 24rpx;
  color: #ccc;
  display: block;
}
</style>